package cn.tedu.csmall.order.service.impl;



import cn.tedu.csmall.commons.exception.CoolSharkServiceException;
import cn.tedu.csmall.commons.pojo.order.dto.OrderAddDTO;
import cn.tedu.csmall.commons.pojo.order.model.OrderTb;
import cn.tedu.csmall.commons.pojo.stock.dto.StockReduceCountDTO;
import cn.tedu.csmall.commons.restful.JsonResult;
import cn.tedu.csmall.commons.restful.ResponseCode;
import cn.tedu.csmall.order.client.CartCilent;
import cn.tedu.csmall.order.client.StockClient;
import cn.tedu.csmall.order.mapper.OrderMapper;
import cn.tedu.csmall.order.service.IOrderService;
import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
@Slf4j
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private StockClient stockClient;

    @Autowired
    private CartCilent cartCilent;


    @Override
    public void orderAdd(OrderAddDTO orderAddDTO) {
        //1.减少订单中的商品的库存(要调用stock模块)
        /**
         * 模拟发送http请求 实现减少商品库存
         *  请求类型POST
         *  url  20002/base/stock/reduce/count
         *   请求参数 StockReduceCountDTO
         */
        StockReduceCountDTO stockReduceCountDTO = new StockReduceCountDTO();
        stockReduceCountDTO.setCommodityCode(orderAddDTO.getCommodityCode());
        stockReduceCountDTO.setReduceCount(orderAddDTO.getCount());
        //第一个参数：要远程调用的模块的方法对应的路径
        //第二个参数：传入协议体内容
        //第三个参数：调用的方法返回值类型
//        restTemplate.postForObject("http://stock/base/stock/reduce/count"
//                ,stockReduceCountDTO
//                , JsonResult.class);
        stockClient.reduceCommodityCount(stockReduceCountDTO);
        System.out.println("远程调用库存模块成功");
        //2.删除订单中勾选的商品购物车
        cartCilent.deleteCartByUserIdAndCommodity(orderAddDTO.getUserId()
                                ,orderAddDTO.getCommodityCode());
        System.out.println("远程调用购物车模块成功");
        //3.新增订单
        OrderTb order = new OrderTb();
        BeanUtils.copyProperties(orderAddDTO, order);
        //执行mapper的新增方法
        int row = orderMapper.insertOrder(order);
        if (row == 0){
            throw new CoolSharkServiceException(ResponseCode.INTERNAL_SERVER_ERROR,"操作数据库失败");
        }
        log.info("订单新增成功:{}", order);
    }
}
